package main

import (
	"github.com/xgdapg/gotp"
	"github.com/xgdapg/wtk"
)

type PluginOTP struct {
	Plugin
}

func init() {
	pluginManager.RegisterPlugin(&PluginOTP{})
}

func (this *PluginOTP) Start() {
	this.Plugin.Start()
	secretKey := this.Data
	if secretKey == "" {
		secretKey = "DEFAULT_SECRET_KEY"
		this.SaveData(secretKey)
	}

	this.RegisterHook(wtk.HookBeforeMethodPost, func(h *wtk.HookHandler) {
		if h.Context.Request.URL.Path == "/admin/login" {
			o := h.Context.GetFormVar("otp")
			if o == "" {
				h.Template.SetVar("ErrMsg", "动态密码验证未通过")
				h.Template.SetTemplateFile(cfg.AdminTplPath() + "/login.tpl")
				h.Render()
				h.Output()
				return
			}
			otp := gotp.NewGoogleAuth(secretKey)
			if otp.GenerateByTime() != o {
				h.Template.SetVar("ErrMsg", "动态密码验证未通过"+otp.GenerateByTime()+","+o)
				h.Template.SetTemplateFile(cfg.AdminTplPath() + "/login.tpl")
				h.Render()
				h.Output()
				return
			}
		}
	})
	this.RegisterHook(wtk.HookAfterRender, func(h *wtk.HookHandler) {
		if h.Context.Request.URL.Path == "/admin/login" {
			this.GetBlock(h, "LoginExtFiled").Append(`<input type="password" class="span12" name="otp" placeholder="One-Time Password">`)
		}
	})
}
